<template>
  <div class="content">
    <div class="date">{{ value }}</div>
    <div class="primary-color" @click="show = true">
      <img style="height: 24px; width: 24px; margin-right: 8px;" src="../assets/calendar.png" alt="" />选择日期
    </div>
    <van-calendar
      :default-date="[currentDate, currentDate]"
      :min-date="minDate"
      :max-date="currentDate"
      v-model="show"
      color="#07c160"
      type="range"
      allow-same-day
      @confirm="onConfirm"
      ref="selectDate"
    >
      <template slot="footer">
        <div class="bottom-button" @click="submit">确定</div>
      </template>
    </van-calendar>
  </div>
</template>

<script>
  import { dateFormat } from '@/utils/index'

  export default {
    name: 'search-date-in-title',
    data() {
      return {
        startDate: dateFormat(new Date(), 'yyyy-MM-dd'),
        endDate: dateFormat(new Date(), 'yyyy-MM-dd'),
        show: false,
        minDate: new Date(2020, 0, 1),
        currentDate: new Date()
      }
    },
    computed: {
      value() {
        if (this.startDate == this.endDate) {
          return this.startDate
        } else {
          return this.startDate + ' - ' + this.endDate
        }
      }
    },
    methods: {
      submit() {
        this.$refs.selectDate.onConfirm()
      },
      onConfirm(data) {
        if (data && data[0]) this.startDate = dateFormat(data[0], 'yyyy-MM-dd')
        if (data && data[1]) this.endDate = dateFormat(data[1], 'yyyy-MM-dd')
        this.show = false
        this.$emit('success', { beginTime: this.startDate, endTime: this.endDate })
      }
    },
    mounted() {
      this.$emit('success', { beginTime: this.startDate, endTime: this.endDate })
    }
  }
</script>

<style lang="less" scoped>
  .primary-color {
    color: #07c160;
    display: flex;
    align-items: center;
  }
  .bottom-button {
    margin-bottom: 16px;
    text-align: center;
    height: 44px;
    line-height: 44px;
    width: 100%;
    font-weight: 500;
    color: #ffffff;
    background: linear-gradient(90deg, #07c160 0%, #90de45 99%);
    border-radius: 16px 16px 16px 16px;
  }
  .content {
    padding: 0 16px;
    font-size: 17px;
    height: 60px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .date {
      font-weight: 500;
      color: #1d2129;
    }
  }
</style>
